package com.zengjianjun.push.msg.platform;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.zengjianjun.push.msg.enums.PushMsgPlatformEnum;
import com.zengjianjun.push.msg.platform.param.BasePushMsgParam;
import com.zengjianjun.push.msg.properties.PushMsgProperties;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

/**
 * @author zengjianjun
 */
@Slf4j
public abstract class AbstractPushMsgClient implements IPushMsgClient {

    @Resource
    protected PushMsgProperties pushMsgProperties;

    protected abstract PushMsgPlatformEnum get();

    protected abstract String convertBody(BasePushMsgParam param);


    @Override
    public void sendMsg(BasePushMsgParam param) {
        this.post(pushMsgProperties.getWebhook(), this.convertBody(param));
    }

    /**
     * 发送post请求
     *
     * @param url  请求链接
     * @param body 请求体
     */
    protected void post(String url, String body) {
        log.info("[{}] start: url = {}", get().name(), url);
        long startTime = System.currentTimeMillis();
        @Cleanup HttpResponse execute = HttpRequest.post(url)
                .body(body)
                .timeout(3000).execute();
        String result = execute.body();
        long endTime = System.currentTimeMillis();
        log.info("[{}] end: result = {}, 耗时 = {}ms", get().name(), result, endTime - startTime);
    }
}
